package com.taobao.pet.service.impl;

import com.taobao.basic.service.impl.BaseServiceImpl;
import com.taobao.pet.domain.PetType;
import com.taobao.pet.mapper.PetTypeMapper;
import com.taobao.pet.service.IPetService;
import com.taobao.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;


    @Override
    public List<PetType> typeTree() {
        // 1.查询所有
        List<PetType> all = petTypeMapper.loadAll();

        // 2.准备一个map
        HashMap<Long, PetType> map = new HashMap<>();

        // 3.把所有数据放入map中
        for (PetType petType : all) {
            map.put(petType.getId(), petType);
        }
        // 4.准备一个list,保存处理之后的数据
        ArrayList<PetType> typeTree = new ArrayList<>();


        for (PetType petType : all) {
            // 顶级部门
            if (petType.getPid() == null) {
                typeTree.add(petType);
            } else {
                // 获取getPid
                Long pid = petType.getPid();
                // 获取上级部门对象
                PetType partDept = map.get(pid);
                // 把自己放入上级部门的children中
                partDept.getChildren().add(petType);
            }
        }
        // 返回类型树
        return typeTree;
    }
}
